package com.xpalive.config.json;

import static com.xpalive.commons.Constants.DateFormatter.DATE;
import static com.xpalive.commons.Constants.DateFormatter.DATE_TIME;

import com.xpalive.commons.Constants;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.Formatter;


/**
 * 为Params请求提供日期格式化支持
 */

@Configuration
public class CustomFormatterConfig {

    @Bean
    public Formatter<LocalDateTime> localDateTimeFormatter() {
        return new Formatter<LocalDateTime>() {
            @Override
            public LocalDateTime parse(String text, Locale locale) {
                return LocalDateTime.parse(text,
                    DateTimeFormatter.ofPattern(DATE_TIME.get()));
            }

            @Override
            public String print(LocalDateTime localDateTime, Locale locale) {
                return DateTimeFormatter.ofPattern(DATE_TIME.get()).format(localDateTime);
            }
        };
    }

    @Bean
    public Formatter<LocalDate> localDateFormatter() {
        return new Formatter<LocalDate>() {
            @Override
            public LocalDate parse(String text, Locale locale) {
                return LocalDate.parse(text, DateTimeFormatter.ofPattern(DATE.get()));
            }

            @Override
            public String print(LocalDate localDate, Locale locale) {
                return DateTimeFormatter.ofPattern(DATE.get()).format(localDate);
            }
        };
    }
}
